<?php
/*
 * Get all posts en reactions.
 */

require_once('rb.php');
R::setup('mysql:host=ftp.giemiebier.nl:3306;dbname=personify', 'school', 'admin123');

//$return = array();

if ($pagetree[2] != "" && isset($pagetree[2])){
    $id = $pagetree[2];
}else{
    $id = "";
}

$return = getMessages($id);

echo json_encode($return);

function getMessages($id){
    $count = R::count('posts', 'userid=? and postid=0',array($id));
    if($count > 0) {
        //$posts['valid'] = true;
        $posts_temp = R::find("posts","userid=? and postid=0",array($id)); //profile.countryid=countries.id
        $i = 0;
        foreach($posts_temp as $post) {
            $b = 0;
            if(R::count('profile', 'userid=?',array($post->userid)) > 0) {
                $post_user = R::findOne("profile","userid=?",array($post->userid));
                $posts[$i]["name"] = $post_user->name;
                $posts[$i]["lastname"] = $post_user->lastname;
            }
            $posts[$i]["id"] = $post->id;
            $posts[$i]["userid"] = $post->userid;
            $posts[$i]["message"] = $post->message;
            $posts[$i]["time"] = $post->time;
            $posts[$i]["postid"] = $post->postid;
            if(R::count('posts', 'postid=?',array($post->id)) > 0) {
                $reactions_temp = R::find("posts","postid=?",array($post->id));
                foreach($reactions_temp as $reaction) {
                    if(R::count('profile', 'userid=?',array($reaction->userid)) > 0) {
                        $reaction_user = R::findOne("profile","userid=?",array($reaction->userid));
                        $posts[$i]["reactions"][$b]["name"] = $reaction_user->name;
                        $posts[$i]["reactions"][$b]["lastname"] = $reaction_user->lastname;
                    }
                    $posts[$i]["reactions"][$b]["id"] = $reaction->id;
                    $posts[$i]["reactions"][$b]["userid"] = $reaction->userid;
                    $posts[$i]["reactions"][$b]["message"] = $reaction->message;
                    $posts[$i]["reactions"][$b]["time"] = $reaction->time;
                    $posts[$i]["reactions"][$b]["postid"] = $reaction->postid;
                    $b++;
                }
                $b = 0;
            }
            else {
                $posts[$i]["reactions"] = "";
            }
            $i++;
        }
    }
    else {
        $posts["error"] = "No messages found";
    }
    return $posts;
}
?>

